package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.wemeida.dtos.WmNewsDto;
import com.heima.model.wemeida.dtos.WmNewsPageReqDto;
import com.heima.model.wemeida.pojos.WmMaterial;
import com.heima.model.wemeida.pojos.WmNews;
import com.heima.model.wemeida.pojos.WmNewsMaterial;
import com.heima.model.wemeida.pojos.WmUser;
import com.heima.utils.common.BeanHelper;
import com.heima.utils.common.JsonUtils;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewMaterialMapper wmNewMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    public ResponseResult<List<WmNews>> findList(WmNewsPageReqDto dto) {
        //参数校验
        dto.checkParam();

        //获取登录用户信息
        WmUser wmUser = (WmUser)ThreadLocalUtils.get();
        if(wmUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //封装条件
        IPage<WmNews> iPage = new Page<>(dto.getPage(),dto.getSize());

        //执行条件查询
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //用户ID
        queryWrapper.eq("user_id",wmUser.getId());
        //状态
        if(dto.getStatus()!=null){
            queryWrapper.eq("status",dto.getStatus());
        }
        //关键字
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            queryWrapper.like("title",dto.getKeyword());
        }
        //频道
        if(dto.getChannelId()!=null){
            queryWrapper.eq("channel_id",dto.getChannelId());
        }
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            queryWrapper.between("publish_time",dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //排序创建时间倒序显示
        queryWrapper.orderByDesc("created_time");

        //封装结果返回
        iPage = page(iPage,queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());
        pageResponseResult.setData(iPage.getRecords());
        pageResponseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        pageResponseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());

        return pageResponseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //获取登录用户信息
        WmUser wmUser = (WmUser)ThreadLocalUtils.get();
        if(wmUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //准备pojo对象
        //拷贝对象属性
        WmNews wmNews = BeanHelper.copyProperties(dto,WmNews.class);
        //补充参数
        wmNews.setUserId(wmUser.getId());//自媒体用户ID
        //补充封面图片
        List<String> coverImage = dto.getImages();
        if(CollectionUtils.isNotEmpty(coverImage)){
            /**
             * Collectors.toList(): 将元素封装成新的List集合
             * Collectors.toSet(): 将元素封装成新的Set集合
             * Collectors.joining(分隔符): 将元素使用指定分隔符拼接成新的字符串
             */
            wmNews.setImages(coverImage.stream().collect(Collectors.joining(",")));//用逗号隔开的字符串
        }

        //一、处理文章的封面图片
        //提取出文章内容的图片
        List<String> contentImages = getImagesFromContent(wmNews);
        if(dto.getType().equals((short)-1)){
            if(contentImages.size()==0){
                //无图
                wmNews.setType((short)0);
                wmNews.setImages(null);
            }
            if(contentImages.size()>=1 && contentImages.size()<=2){
                //单图
                wmNews.setType((short)1);
                wmNews.setImages(contentImages.get(0));
            }
            if(contentImages.size()>=3){
                //三图
                wmNews.setType((short)3);
                //contentImages.subList(0,3): 从List集合中截取前三张图片
                wmNews.setImages(contentImages.subList(0,3).stream().collect(Collectors.joining(",")));
            }
        }

        //二、判断新增还是修改
        if(dto.getId()==null){
            //保存pojo对象
            wmNews.setCreatedTime(new Date());
            wmNews.setSubmitedTime(new Date());
            wmNewsMapper.insert(wmNews);
        }else{
            //修改文章
            wmNewsMapper.updateById(wmNews);

            //删除该文章与素材的关联
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("news_id",dto.getId());
            wmNewMaterialMapper.delete(queryWrapper);
        }

        //三、建立该文章与素材的关联
        //建立文章与内容素材的关联（type=0）
        if(contentImages.size()>0){
            //找到内容素材的ID
            List<Integer> materialIds = getMaterialIdFromUrl(contentImages);
            if(CollectionUtils.isNotEmpty(materialIds)){
                wmNewMaterialMapper.saveNewsMaterial(materialIds,wmNews.getId(),0);
            }
        }

        //建立文章与封面素材的关联（type=1）
        String coverImages = wmNews.getImages();
        if(StringUtils.isNotEmpty(coverImages)){
            List<String> list = Arrays.asList(coverImages.split(","));
            List<Integer> materialIds = getMaterialIdFromUrl(list);
            if(CollectionUtils.isNotEmpty(materialIds)){
                wmNewMaterialMapper.saveNewsMaterial(materialIds,wmNews.getId(),1);
            }
        }

        //判断只有提交审核才进入自动审核流程
        if(dto.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据素材的URL查询素材ID
     * @param contentImages
     * @return
     */
    private List<Integer> getMaterialIdFromUrl(List<String> contentImages) {
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("url",contentImages);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        return wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
    }

    /**
     * 提取文章内容中的图片路径
     * @param wmNews
     * @return
     */
    private List<String> getImagesFromContent(WmNews wmNews) {
        List<String> imageList = new ArrayList<>();
        if(wmNews!=null && StringUtils.isNotEmpty(wmNews.getContent())){
            List<Map> list = JsonUtils.toList(wmNews.getContent(), Map.class);
            for(Map map : list){
                if(map.get("type").equals("image")){
                    imageList.add((String)map.get("value"));
                }
            }
        }
        return imageList;
    }
}
